package com.ziqikeji.xianyan.service.comment;

import com.ziqikeji.xianyan.common.BaseService;
import com.ziqikeji.xianyan.entity.article.Article;
import com.ziqikeji.xianyan.entity.comment.Comment;
import com.ziqikeji.xianyan.enumeration.DeleteFlagEnum;
import com.ziqikeji.xianyan.repository.comment.CommentDao;
import com.ziqikeji.xianyan.service.article.ArticleService;
import com.ziqikeji.xianyan.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 评论 service
 *
 * @author liuyu
 */
@Service
public class CommentService extends BaseService<Comment, CommentDao> {

    private static final String NO_LOGIN_USER_MARK = "anonymousUser";
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;

    /**
     * 保存评论
     *
     * @param articleId 文章id
     * @param content   评论内容
     * @return 评论
     */
    public Comment saveComment(String articleId, String content) {
        Article article = this.articleService.get(articleId);
        Comment comment = new Comment();
        comment.setArticle(article);
        comment.setContent(content);
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!NO_LOGIN_USER_MARK.equals(principal)) {
            User user = (User) principal;
            com.ziqikeji.xianyan.entity.user.User sysUser = this.userService.getByLoginName(user.getUsername());
            comment.setUser(sysUser);
        }
        comment.setLikeNumber((long) 0);
        comment.setTime(new Date(System.currentTimeMillis()));
        return super.save(comment);
    }

    /**
     * 获取文章下的所有评论
     *
     * @param articleId 文章ID
     * @return 返回文章列表
     */
    public List<Comment> getByArticle(String articleId) {
        return this.commentDao.findCommentsByArticleIdAndDeleteFlagEnum(articleId, DeleteFlagEnum.NO_DELETE);
    }
}
